package com.yssoft.service.publicPlatform;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;

import com.yssoft.common.Constants;
import com.yssoft.entity.core.TEnterpriseLicence;
import com.yssoft.entity.supplier.ProductionBatch;
import com.yssoft.entity.supplier.TEnterpriseCustom;
import com.yssoft.mapper.publicPlatform.PublicTraceMapper;
import com.yssoft.mapper.traceability.TTraceProcessMapper;
import com.yssoft.mapper.traceability.TTraceQuotaMapper;
import com.yssoft.service.core.EnterpriseService;
import com.yssoft.service.production.ProductionProcessService;
import com.yssoft.service.sales.DealerService;
import com.yssoft.service.supervise.FlowQueryService;
import com.yssoft.service.supervise.ProductionDetectionService;
import com.yssoft.service.supervise.TraceabilityQueryService;
import com.yssoft.utils.AppUserHelper;

@Service
public class PublicTraceService {
	@Resource
    private ProductionDetectionService productionDetectionService;
    @Resource
    private ProductionProcessService productionProcessService;
	@Resource
	private DealerService dealerService;
	@Resource
    private FlowQueryService flowQueryService;
	@Resource
	private EnterpriseService enterpriseService;
	@Resource
    private  TraceabilityQueryService traceabilityQueryService;
	@Resource
	private PublicTraceMapper publicTraceMapper;
	@Resource
	private TTraceQuotaMapper tTraceQuotaMapper;
	@Autowired
	private TTraceProcessMapper traceProcessMapper;
 
	public Model  lableCodeTrace(Model model, String labelCode) {
		//记录扫描数据
		publicTraceMapper.updateLableScanNum(labelCode);
		
		//条件查询
		Map<String, Object>  map = null;
		if(StringUtils.isNoneBlank(labelCode)) {
			map=traceabilityQueryService.queryWorksheetIdByLabelCode(labelCode);
		}
		if(map!=null&& map.get("worksheetId")!=null) {
			Integer worksheetId=Integer.valueOf(map.get("worksheetId")+"");
			
			ProductionBatch custom=new ProductionBatch();
			custom.setWorksheetId(worksheetId);
			//1.1商品信息
			Map<String, Object>  product=traceabilityQueryService.queryProductByWorksheetId(custom);
			int	scanNum=publicTraceMapper.queryLableScanNumByCode(labelCode);
			product.put("scanNum", scanNum);
			Integer productId=( null==product.get("productId") )?0:Integer.valueOf(product.get("productId")+"");
			//1.2企业信息
			TEnterpriseCustom  enterprise=traceabilityQueryService.queryEnterpriseById(custom);
	    	Map<String, Object> enterpriseMap=new HashMap<>();
	    	if(enterprise!=null) {
	    		enterpriseMap.put("name", enterprise.getName());
	    		enterpriseMap.put("legalPerson", enterprise.getLegalPerson());
	    		enterpriseMap.put("code", enterprise.getCode());
	    		enterpriseMap.put("regAddress", enterprise.getRegAddress());
	    		enterpriseMap.put("phone", enterprise.getPhone());
	    		enterpriseMap.put("website", enterprise.getWebsite());
	    		enterpriseMap.put("logoImg", enterprise.getLogoImg());
	    		//企业证照信息1-生产许可证
		    	TEnterpriseLicence licence1 = enterpriseService.queryLicenceByCode(enterprise.getId(),"1");
		    	//企业证照信息2-营业执照
		    	TEnterpriseLicence licence2 = enterpriseService.queryLicenceByCode(enterprise.getId(),"2");
		    	if(licence1!=null) {
		    		enterpriseMap.put("licence1", licence1.getLicenceImg());
		    	}
		    	if(licence2!=null) {
		    		enterpriseMap.put("licence2", licence2.getLicenceImg());
		    	}
	    	}
	    	 
			//2采购信息
	    	List<Map<String, Object>> materialList=queryProcurementInfoListByWorksheetId(productId, worksheetId);
			//3检验信息
	    	List<Map<String, Object>> inspectionReportList = productionDetectionService.selectInspectionReport(worksheetId+"");
	    	Map<String, Object> inspectionReport=null;
	    	if(inspectionReportList!=null && inspectionReportList.size()>0) {
	    		inspectionReport=inspectionReportList.get(0);
	    	}
			//4生产信息
	    	Map<String, Object> productionInfo =queryProductionInfo(labelCode);
			//5流通信息
			if (product!=null&&null!=product.get("traceabilityType") && "1".equals(product.get("traceabilityType")+"")) {
				Map<String, Object> circulationMap =queryCirculationInfo(labelCode);
				model.addAttribute("circulation",circulationMap);
			}
			model.addAttribute("materialList",materialList);
			model.addAttribute("product",product);
			model.addAttribute("enterprise",enterpriseMap);
			model.addAttribute("inspectionReport",inspectionReport);  
			model.addAttribute("productionInfo",productionInfo);
	 
		}
 
 		return model;
	}
	/**
	 * 
	    * @Title: queryProductionInfo
	    * @Description: 生产信息
	    * @param @param labelCode
	    * @param @return    参数
	    * @return List<ProductionInfo>    返回类型
	    * @throws
	 */
	private Map<String, Object> queryProductionInfo(String labelCode) {
		//查询详情
		Map<String, Object> infoMap = flowQueryService.queryFlowMap(labelCode);
		//查询包装时间
		Map<String, Object> map=publicTraceMapper.queryLablePackDate(labelCode);
		if(map!=null ) {
			infoMap.put("packDate", map.get("pcCreateTime"));
		}
		return infoMap;
	}
	/**
	 * 
	    * @Title: queryCirculationInfoList
	    * @Description: 根据个体码和加工单查询流通信息
	    * @param @param custom
	    * @param @param labelCode
	    * @param @return    参数
	    * @return Map<String,Object>    返回类型
	    * @throws
	 */
	private Map<String, Object> queryCirculationInfo(  String labelCode) {
		//流通信息 
		Map<String, Object> circulation = flowQueryService.queryFlowMap(labelCode);
		//订购数量查询
		Map<String, Object>  detail=publicTraceMapper.queryFlowMapDetail(labelCode);
		if(detail!=null) {
			circulation.put("quantity", detail.get("quantity"));
			Map<String,Object> custom =null;
			if(null!=detail.get("cId") &&  !"".equals( detail.get("cId")  )) {
				custom= dealerService.findDetail(Integer.valueOf(detail.get("cId")+""));
			}
			if(custom!=null) {
				//data.put("imgUrl"+img.get("type"), img.get("url"));
				//营业执照
				circulation.put("yyImgUrl", custom.get("imgUrl2"));
				//生产许可
				circulation.put("ltImgUrl", custom.get("imgUrl1"));
				circulation.put("eName", custom.get("name"));
				circulation.put("legalPerson",  custom.get("legal_person"));
				circulation.put("creditCode",  custom.get("credit_code"));
			}
			
		}
		 
		return circulation;
	}
	/**
	 * 
	 * @param productId
	 * @param worksheetId
	 * @return #物料信息，收货信息，入库信息，检验信息,采购信息
	 */
	private List<Map<String, Object>>   queryProcurementInfoListByWorksheetId(Integer productId,Integer worksheetId){
		if (null==productId) return null;
		//根据产品id查询所需要显示的(物料信息)
		/*m.id materialId,m.name materialName,m.specifications,m.unit,dd.classify */
		List<Map<String, Object>> materialList=publicTraceMapper.queryMaterialListByProductId(productId);
		if(materialList!=null && materialList.size()>0) {
			for(Map<String, Object> material:materialList) {
				//根据物料id查询以下信息
				if( null!=material.get("materialId")&&StringUtils.isNoneBlank(material.get("materialId")+"")) {
					String materialId=material.get("materialId")+"";
					List<Map<String, Object>> maxCollarMaterialDetailIdList=null;
					List<Map<String, Object>> outstockDetailList=null;
					List<Map<String, Object>> maxInstockDetailList=null;
					List<Map<String, Object>> instockDetailList=null;
					List<Map<String, Object>> recipientDetailList=null;
					List<Map<String, Object>> inspectionReportList=null;
					//选出物料对应的最新的领料记录明细Id
					maxCollarMaterialDetailIdList=publicTraceMapper.queryMaxCollarMaterialDetailId(materialId,worksheetId);
					//#根据最新的领料记录明细Id->最新出库申请明细id->出库明细id
					if(null!=maxCollarMaterialDetailIdList && maxCollarMaterialDetailIdList.size()>0 ) {
						outstockDetailList=publicTraceMapper.queryOutstockDetailListByMaxCollarMaterialDetailId(worksheetId,maxCollarMaterialDetailIdList);
					}
					//#根据出库明细id-获得最新入库明细id
					if(null!=outstockDetailList && outstockDetailList.size()>0 ) {
						maxInstockDetailList=publicTraceMapper.queryMaxInstockDetailListByOutstockDetailIds(outstockDetailList);
					}
					//入库时间和入库仓库(入库信息)
					if(null!=maxInstockDetailList && maxInstockDetailList.size()>0 ) {
						instockDetailList=publicTraceMapper.queryInstockDetailListByMaxIds(maxInstockDetailList);
						if(instockDetailList!=null && instockDetailList.size()>0) {
							Map<String, Object> map=instockDetailList.get(0);
							material.putAll(map);
						}
					}
					
					 
					//根据入库明细id->入库申请明细-(检验信息)
					//根据入库明细id->入库申请明细->收货单明细 生产批次，生产时间，收货明细id(收货信息)
					if(null!=maxInstockDetailList && maxInstockDetailList.size()>0 ) {
						recipientDetailList=publicTraceMapper.queryRecipientDetailListByMaxInstockId(maxInstockDetailList);
						if(recipientDetailList!=null && recipientDetailList.size()>0) {
							Map<String, Object> map=recipientDetailList.get(0);
							material.putAll(map);
						}
						inspectionReportList=publicTraceMapper.queryInspReportList(maxInstockDetailList);
						if(null!=inspectionReportList && inspectionReportList.size()>0) {
							Map<String, Object> map=inspectionReportList.get(0);
							Integer id  =(map.get("id")== null)?0: Integer.valueOf(map.get("id")+"");
							//并查询明细信息
							List<Map<String, Object>> reportDetailList=publicTraceMapper.queryInspReportDetail( id,null );
							//并查询附件信息
							List<Map<String, Object>> reportAttrList=publicTraceMapper.queryInspReportAttrList(id,null);
							map.put("reportDetailList", reportDetailList);
							map.put("reportAttrList", reportAttrList);
							material.putAll(map);
						}
						
					}
					//根据收获明细id获取收获附件(收获附件信息，采购信息)
					if(null!=recipientDetailList && recipientDetailList.size()>0) {
						//收货信息
						Map<String, Object> recipientDetail = recipientDetailList.get(0);
						Integer rdId  =(null==recipientDetail.get("rdId"))?0:Integer.valueOf(recipientDetail.get("rdId")+"");
						List<Map<String, Object>> purchaseDetailList=publicTraceMapper.queryPurchaseDetailList(rdId);
						List<Map<String, Object>> recipientAttrList=publicTraceMapper.queryRecipientAttrList(recipientDetailList);
						List<Map<String, Object>>  tradeAttList=new ArrayList<>();
						List<Map<String, Object>>  certificateOriginAttList=new ArrayList<>();

						if(recipientAttrList!=null && recipientAttrList.size()>0) {
							Map<String, Object> map=recipientAttrList.get(0);
							String type=map.get("type")+"";
							//交易凭证
							if("1".equals(type)) {
								tradeAttList.add(map);
							}
							//产地合格证书
							if("2".equals(type)) {
								certificateOriginAttList.add(map);
							}
						}
						if(null!=purchaseDetailList && purchaseDetailList.size()>0) {
							Map<String, Object> map=purchaseDetailList.get(0);
							material.putAll(map);
						}
						material.put("tradeAttList", tradeAttList);
						material.put("certificateOriginAttList", certificateOriginAttList);
					}
				}
			}
		}
		return materialList;
	}
 
	public List<Map<String, Object>> findTechnologyByProduct(HttpServletRequest request) {
		Map<String,Object> param = new HashMap<>();
		param.put("deleteFlag", "0");
		return traceProcessMapper.queryTraceProcess(param);
	}
	public List<Map<String, Object>> findIndexAndValueByProcessingTechnic(String technologyId, String recipientId) {
		Map<String,Object> param = new HashMap<>();
		param.put("processId", technologyId);
		param.put("recipientId", recipientId);
		return tTraceQuotaMapper.queryTraceQuotaList(param);
	}
	public Map<String, Object> productTrace(String labelCode) {
		//条件查询
		Map<String, Object>  map = null;
		if(StringUtils.isNoneBlank(labelCode)) {
			map=traceabilityQueryService.queryWorksheetIdByLabelCode(labelCode);
		}
		if(map!=null&& map.get("worksheetId")!=null) {
			Integer worksheetId=Integer.valueOf(map.get("worksheetId")+"");
			ProductionBatch custom=new ProductionBatch();
			custom.setWorksheetId(worksheetId);
			//1.1商品信息
			Map<String, Object>  product=traceabilityQueryService.queryProductByWorksheetId(custom);
			int	scanNum=publicTraceMapper.queryLableScanNumByCode(labelCode);
			product.put("scanNum", scanNum);
			 
			//1.2企业信息
			TEnterpriseCustom  enterprise=traceabilityQueryService.queryEnterpriseById(custom);
	    	Map<String, Object> enterpriseMap=new HashMap<>();
	    	if(enterprise!=null) {
	    		enterpriseMap.put("name", enterprise.getName());
	    		enterpriseMap.put("legalPerson", enterprise.getLegalPerson());
	    		enterpriseMap.put("code", enterprise.getCode());
	    		enterpriseMap.put("regAddress", enterprise.getRegAddress());
	    		enterpriseMap.put("phone", enterprise.getPhone());
	    		enterpriseMap.put("website", enterprise.getWebsite());
	    		enterpriseMap.put("logoImg", enterprise.getLogoImg());
	    		//企业证照信息1-生产许可证
		    	TEnterpriseLicence licence1 = enterpriseService.queryLicenceByCode(enterprise.getId(),"1");
		    	//企业证照信息2-营业执照
		    	TEnterpriseLicence licence2 = enterpriseService.queryLicenceByCode(enterprise.getId(),"2");
		    	if(licence1!=null) {
		    		enterpriseMap.put("licence1", licence1.getLicenceImg());
		    	}
		    	if(licence2!=null) {
		    		enterpriseMap.put("licence2", licence2.getLicenceImg());
		    	}
	    	}
	    	//合并产品和企业信息
	    	map.putAll( product );
	    	map.putAll( enterpriseMap );
		}
		return map;
	}
	public Map<String, Object> productionTrace(String labelCode) {
		//条件查询
		Map<String, Object>  map = null;
		if(StringUtils.isNoneBlank(labelCode)) {
			map=traceabilityQueryService.queryWorksheetIdByLabelCode(labelCode);
		}
		if(map!=null&& map.get("worksheetId")!=null) {
			Integer worksheetId=Integer.valueOf(map.get("worksheetId")+"");
			ProductionBatch custom=new ProductionBatch();
			custom.setWorksheetId(worksheetId);
			//4生产信息
	    	Map<String, Object> productionInfo =queryProductionInfo(labelCode);
	    	map.putAll(productionInfo);
		}
		return map;
	}
	public Map<String, Object> inspectionTrace(String labelCode) {
		//条件查询
		Map<String, Object>  map = null;
		if(StringUtils.isNoneBlank(labelCode)) {
			map=traceabilityQueryService.queryWorksheetIdByLabelCode(labelCode);
		}
		if(map!=null&& map.get("worksheetId")!=null) {
			Integer worksheetId=Integer.valueOf(map.get("worksheetId")+"");
			ProductionBatch custom=new ProductionBatch();
			custom.setWorksheetId(worksheetId);
		   //3检验信息
	    	List<Map<String, Object>> inspectionReportList = productionDetectionService.selectInspectionReport(worksheetId+"");
	    	Map<String, Object> inspectionReport=null;
	    	if(inspectionReportList!=null && inspectionReportList.size()>0) {
	    		inspectionReport=inspectionReportList.get(0);
	    	}
	    	map.putAll(inspectionReport);
		}
		return map;
	}
	public Map<String, Object> circulationTrace(String labelCode) {
		//条件查询
		Map<String, Object>  map = null;
		if(StringUtils.isNoneBlank(labelCode)) {
			map=traceabilityQueryService.queryWorksheetIdByLabelCode(labelCode);
		}
		if(map!=null&& map.get("worksheetId")!=null) {
			Integer worksheetId=Integer.valueOf(map.get("worksheetId")+"");
			ProductionBatch custom=new ProductionBatch();
			custom.setWorksheetId(worksheetId);
			//1.1商品信息
			Map<String, Object>  product=traceabilityQueryService.queryProductByWorksheetId(custom);
			//5流通信息
			if (product!=null&&null!=product.get("traceabilityType") && "1".equals(product.get("traceabilityType")+"")) {
				Map<String, Object> circulationMap =queryCirculationInfo(labelCode);
				map.putAll(circulationMap);
			}
		}
		return map;
	}
 
	public List<Map<String, Object>> recipientTraceListByRecipientId(String recipientId) {
		  List<Map<String,Object>> straceProcessList =null;
		if(null!=recipientId && !"".equals(recipientId)) {
		      straceProcessList = traceProcessMapper.selectTraceProByRecipientId(Integer.valueOf(recipientId));
				for(Map<String, Object> sgMap : straceProcessList){
					if(null != sgMap){
						Map<String, Object> param = new HashMap<String, Object>();
						param.put("processId", sgMap.get("id"));
						param.put("recipientId", recipientId);
						param.put("shareStat", "1");
						List<Map<String,Object>> straceGatherList = tTraceQuotaMapper.queryTraceQuotaList(param);
						sgMap.put("straceGatherList", straceGatherList);
					}
				}
		}
		 return straceProcessList;
	}
	/**
	 * 
	 * @param
	 * @return
	 */
	public List<Map<String, Object>> findTechnologyByRecipientId(String recipientId) {
		Map<String,Object> param = new HashMap<>();
		param.put("deleteFlag", "0");
		if(StringUtils.isNoneBlank(recipientId)) {
			Integer tEId=publicTraceMapper.queryTEIdByRecipientId(recipientId);
			param.put("tEId",tEId );
			return traceProcessMapper.queryTraceProcess(param);
		}else {
			return null;
		}
		
	}
	
}
